//
//  WCG_O_DetailViewController.m
//  Project_B
//
//  Created by 黑黑 on 15/11/24.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WCG_O_DetailViewController.h"
#import "GXiaNetHandle.h"
#import "GXSpecialModel.h"
#import "GXSpecialClickModel.h"
#import "GXSuggestModel.h"
#import "GXProviderDataModel.h"
#import "WCG_O_sectionHeaderView.h"
#import "WCG_O_SingleTableViewCell.h"
#import "WCG_O_SingleCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"
#import "WCG_O_DetailProviderViewController.h"
#import "WCG_O_SingleCollectionViewCell.h"
#import "WCG_O_DetailItemViewController.h"
#import "GXProviderDetailTableViewCell.h"
#import "WCG_O_ChatViewController.h"
#import "WCG_O_MapViewController.h"
#import "MBProgressHUD.h"
#import "SpecialModel.h"

@interface WCG_O_DetailViewController () <UITableViewDataSource, UITableViewDelegate, WCG_O_pushDelegate>

@property (nonatomic, strong) NSMutableArray *item_listArr;
@property (nonatomic, strong) NSMutableArray *cp_listArr;
@property (nonatomic, strong) GXSpecialModel *specialModel;
@property (nonatomic, strong) UITableView *contentTableView;
@property (nonatomic, strong) UITableView *providerTableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *titleLable;
@property (nonatomic, strong) UILabel *subtitleLable;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) WCG_O_SingleTableViewCell *cell;
@property (nonatomic, assign) CGFloat headHight;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) UIButton *readButton;
@property (nonatomic, assign) BOOL readSpe;
@property (nonatomic, assign) NSInteger cellIndex;
@end



@implementation WCG_O_DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
//    [self getSpecialDetailData];

    // 创建tableVie
#if 1
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight + 49) style:UITableViewStyleGrouped];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.bounces = NO;
    self.myTableView.scrollsToTop = YES;
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.contentInset = UIEdgeInsetsMake(350, 0, 0, 0);
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[WCG_O_SingleTableViewCell class] forCellReuseIdentifier:@"cell"];
#endif
    [self loadNightMBProgress];
    // 创建底部按钮
    [UIView animateWithDuration:1.5 animations:^{
        [self createButtomBackButtonIsHiddenShareBtn:YES];
        [self.backBtn addTarget:self action:@selector(backTofront) forControlEvents:UIControlEventTouchUpInside];
    }];
    // 通知中心跳转
    NSNotificationCenter *contentCenter = [NSNotificationCenter defaultCenter];
    [contentCenter addObserver:self selector:@selector(contentAction:) name:@"content" object:nil];
    NSNotificationCenter *proCenter = [NSNotificationCenter defaultCenter];
    [proCenter addObserver:self selector:@selector(proAction:) name:@"pro" object:nil];
    NSNotificationCenter *map = [NSNotificationCenter defaultCenter];
    NSNotificationCenter *chat = [NSNotificationCenter defaultCenter];
    [map addObserver:self selector:@selector(mapAction) name:@"map" object:nil];
    [chat addObserver:self selector:@selector(chatAction) name:@"chat" object:nil];
    
    [self getSpecialDetailData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *tabbarView = temp[2];
    [UIView animateWithDuration:1 animations:^{
        tabbarView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
    self.navigationController.navigationBarHidden = YES;
    // 判断按钮
//    [self getSpecialDetailData];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"special_id = %@",self.specialID];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"special_id" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"查询为空");
    }
    if (fetchedObjects.count != 0) {
        for (SpecialModel *spe in fetchedObjects) {
            if (![spe.special_id isEqualToNumber:self.specialID]) {
                self.readSpe = NO;
            }else{
                self.readSpe = YES;
            }
        }
    }
    [self addSubViewHeaderView];
}

- (void)createHeader {
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 350)];
    self.headHight = 350;
    //    self.myTableView.tableHeaderView = self.headerView;
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -350, kScreenWidth, 350)];
    UIImage *temp = [self getBrighterImage:self.imageView.image];
    self.imageView.image = temp;
    [self.imageView sd_setImageWithURL:_specialModel.thumb[@"raw"]];
    //设置imageView高度改变时宽度也跟着改变
    self.imageView.userInteractionEnabled = YES;
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.layer.masksToBounds = YES;
    [self.myTableView addSubview:self.imageView];
    
    self.titleLable = [[UILabel alloc] init];
    self.titleLable.textAlignment = NSTextAlignmentCenter;
    self.titleLable.font = [UIFont fontWithName:@"FZSongKeBenXiuKaiS-R-GB" size:25];
    self.titleLable.textColor = [UIColor whiteColor];
    [self.imageView addSubview:self.titleLable];
    [self.titleLable setText:_specialModel.title];
    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.imageView.mas_centerX);
        make.centerY.mas_equalTo(self.imageView.mas_centerY);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(300);
    }];
    
    self.subtitleLable = [[UILabel alloc] initWithFrame:CGRectZero];
    self.subtitleLable.textAlignment = NSTextAlignmentCenter;
    self.subtitleLable.numberOfLines = 0;
    self.subtitleLable.font = [UIFont systemFontOfSize:15];
    self.subtitleLable.textColor = [UIColor whiteColor];
    [self.subtitleLable setText:_specialModel.content[@"desc"]];
    [self.imageView addSubview:self.subtitleLable];
    
    [self.subtitleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLable.mas_bottom).with.offset(10);
        make.left.mas_equalTo(self.imageView.mas_left).with.offset(5);
        make.right.mas_equalTo(self.imageView.mas_right).with.offset(-5);
        make.height.mas_equalTo(100);
    }];
    self.readButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.readButton.layer.cornerRadius = 15;
    [self.imageView addSubview:self.readButton];
    [self.readButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.imageView.mas_centerX);
        make.top.mas_equalTo(self.subtitleLable.mas_bottom).with.offset(40);
        make.bottom.mas_equalTo(self.imageView.mas_bottom).with.offset(-20);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
    if (self.readSpe) {
        self.readButton.backgroundColor = [UIColor grayColor];
        [self.readButton setTitle:@"已订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor whiteColor];
    }else
    {
        self.readButton.backgroundColor = [UIColor colorWithRed:253/255.0 green:215/255.0 blue:80/255.0 alpha:1];
        [self.readButton setTitle:@"订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor blackColor];
    }
    [self.readButton addTarget:self action:@selector(readAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)addSubViewHeaderView
{
    if (self.readSpe) {
        self.readButton.backgroundColor = [UIColor grayColor];
        [self.readButton setTitle:@"已订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor whiteColor];
    }else
    {
        self.readButton.backgroundColor = [UIColor colorWithRed:253/255.0 green:215/255.0 blue:80/255.0 alpha:1];
        [self.readButton setTitle:@"订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor blackColor];
    }
    [self.readButton addTarget:self action:@selector(readAction) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 订阅按钮(收藏specialModel)
- (void)readAction
{

    if (!self.readSpe) {
        [self.readButton setTitle:@"已订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor whiteColor];
        self.readButton.backgroundColor = [UIColor grayColor];
        // 添加
        SpecialModel *special = [NSEntityDescription insertNewObjectForEntityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
        special.title = self.specialModel.title;
        special.special_id = self.specialModel.special_id;
        special.content_num = self.specialModel.content_num;
        special.subscriber_num = self.specialModel.subscriber_num;
        special.title_font = self.specialModel.thumb[@"raw"];
        special.type = @"special";
        
        [self.manager saveContext];
    }else
    {
        [self.readButton setTitle:@"订阅" forState:UIControlStateNormal];
        self.readButton.tintColor = [UIColor blackColor];
        self.readButton.backgroundColor = [UIColor colorWithRed:253/255.0 green:215/255.0 blue:80/255.0 alpha:1];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"SpecialModel" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", self.specialModel.title];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"空空空~");
        }
        for (SpecialModel *s in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:s];
        }
        [self.manager saveContext];
        
    }
    self.readSpe = !self.readSpe;
}

#pragma mark - 请求数据
- (void)getSpecialDetailData {
    NSString *str = [NSString stringWithFormat:kSpecialDetailWeb, self.specialID, 1L];
    [GXiaNetHandle getUrl:str cookie:kSpecialDetailCookie success:^(id result) {
        NSDictionary *dic = result;
        self.page = [result[@"page"] integerValue];
        //specialClickModel 里的 item_list 里装的是推荐model
        //specialClickModel 里的 cp_list 里装的是造物者 model
        GXSpecialClickModel *specialClickModel = [GXSpecialClickModel modelWithDic:dic];
        
        //将字典转模型装到数组里/推荐
        self.item_listArr = [GXSuggestModel transformWithArray:specialClickModel.item_list];
        //将字典转模型装到数组里/造物者
        self.cp_listArr = [GXProviderDataModel transformWithArray:specialClickModel.cp_list];
        //专题信息
        self.specialModel = [GXSpecialModel modelWithDic:specialClickModel.special];

        [self createHeader];
        [self.myTableView reloadData];
        [self.hud removeFromSuperview];
        UIImageView *buttonView = (UIImageView *)[self.view viewWithTag:2000];
        [UIScrollView animateWithDuration:0.1 animations:^{
            
            buttonView.frame = CGRectMake(kScreenWidth / 3.0 * self.cellIndex, 0, kScreenWidth / 3.0, 64);
        }];
    } failure:^(NSError *error) {
    }];
}

#pragma mark - tableView方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    //将解析的数组赋给collectionView的属性
    self.cell.itemArr = self.item_listArr;
    self.cell.cpArr = self.cp_listArr;
    self.cell.specialModel = self.specialModel;
    [self.cell.collectionView reloadData];
    return self.cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenHeight - 49;
}

#pragma mark - sectionHeader
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 64;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    
    NSArray *buttonTitleArr = @[@"内容", @"造物主", @"订阅"];
    for (int i = 0; i < 3; i++) {
        NSString *titleStr = buttonTitleArr[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 1000 + i;
        button.frame = CGRectMake(kScreenWidth / 3.0 * i, 0, kScreenWidth / 3.0, 64);
        [button setTitle:titleStr forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:@"FZSongKeBenXiuKaiS-R-GB" size:20];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
    
    //设置一个button底部的图片.通过scrollView的滑动.改变他的偏移量.
    UIImageView *buttonView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"详情中部选中背景"]];
    buttonView.frame = CGRectMake(0, 0, kScreenWidth / 3.0, 64);
    buttonView.tag = 2000;
    [view addSubview:buttonView];
    
    return view;
}

- (void)buttonClick:(UIButton *)button
{
    UIImageView *buttonView = (UIImageView *)[self.view viewWithTag:2000];
    
    
    NSInteger index = 1000;
    
    switch (button.tag) {
        case 1000:
            
            index = 1000 - index;
            //NSLog(@"ss");
            break;
        case 1001:
            
            index = 1001 - index;
            //NSLog(@"ss1");
            break;
        case 1002:
            index = 1002 - index;
            //NSLog(@"ss2");
            break;
        default:
            break;
    }
    
    [UIScrollView animateWithDuration:0.1 animations:^{
        
        buttonView.frame = CGRectMake(kScreenWidth / 3.0 * index, 0, kScreenWidth / 3.0, 64);
    }];
    
    self.index = index;
    [self.cell changeCollectionByIndex:index];
}

- (void)changButtonViewByIndex:(CGFloat)index{
    UIImageView *buttonView = (UIImageView *)[self.view viewWithTag:2000];
    
    buttonView.frame = CGRectMake(kScreenWidth / 3.0 * index, 0, kScreenWidth / 3.0, 64);
    self.index = index;
    
    WCG_O_SingleTableViewCell *tableViewCell = [self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UICollectionView *collectionView = tableViewCell.collectionView;
    
    WCG_O_SingleCollectionViewCell *collectionCell = (WCG_O_SingleCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.index inSection:0]];
    UITableView *table = collectionCell.tableView;
    
    if (self.myTableView.contentOffset.y < -1) {
        
        table.scrollEnabled = NO;
        
    } else {
        
        table.scrollEnabled = YES;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//判断外部的scrollerView 的滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
//    //刚开始y的偏移量初始值就是-264
    NSLog(@"y1 === %f",scrollView.contentOffset.y);
    CGFloat y = scrollView.contentOffset.y;//加上导航栏高度,第一次是-200
    NSLog(@"y2 === %f",y);
    if (y < -350) {
        CGRect frame = self.imageView.frame;
        frame.origin.y = y;//imageView的frame是不断往上偏移
        frame.size.height =  -y;//tablview向下偏移了多少,高度就增加多少
        self.imageView.frame = frame;
        self.coverView.frame = frame;
    }
//
    
    WCG_O_SingleTableViewCell *tableViewCell = [self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
  
    //tableView内部的cell里面的collectionView
    UICollectionView *collectionView = tableViewCell.collectionView;
    
    //tableView内部的cell里面的collectionView的cell
    WCG_O_SingleCollectionViewCell *collectionCell = (WCG_O_SingleCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.index inSection:0]];
    
    //tableView内部的cell里面的collectionView的cell的tableView(就是一个tableView)
    UITableView *table = collectionCell.tableView;
    //NSLog(@"%f", self.tableView.contentOffset.y);
    //NSLog(@"%f", self.headHight);
    
    if (self.myTableView == scrollView) {
        if (self.myTableView.contentOffset.y < -1) {
        
            table.scrollEnabled = NO;
            
        } else {
            table.scrollEnabled = YES;
            
        }
    }
    // 按钮
    static CGFloat yy;
    if (scrollView.contentOffset.y > yy) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0;
            self.repostBtn.alpha = 0;
            self.likeBtn.alpha = 0;
        }];
        yy = scrollView.contentOffset.y;
    }
    if (scrollView.contentOffset.y <= yy) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0.8;
            self.repostBtn.alpha = 0.8;
            self.likeBtn.alpha = 0.8;
        }];
        yy = scrollView.contentOffset.y;
    }
}

#pragma mark - 按钮点击事件
- (void)backTofront
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark - 实现协议方法
- (void)pushContentWithModel:(GXSuggestModel *)suggestModel
{
    WCG_O_DetailItemViewController *detailVC = [[WCG_O_DetailItemViewController alloc] init];
    detailVC.suggestModel = suggestModel;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)pushProWithModel:(GXProviderDataModel *)proModel
{
    WCG_O_DetailProviderViewController *detailVc = [[WCG_O_DetailProviderViewController alloc] init];
    detailVc.providerModel = proModel;
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark - 跳转的通知中心方法
- (void)contentAction:(NSNotification *)note
{
    WCG_O_DetailItemViewController *detailVC = [[WCG_O_DetailItemViewController alloc] init];
    detailVC.suggestModel = note.userInfo[@"content"];
    detailVC.url = [note.userInfo[@"content"] item_url];
    detailVC.titleStr = [note.userInfo[@"content"] title];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.cellIndex = [note.userInfo[@"index"] integerValue];
    
}

- (void)proAction:(NSNotification *)note
{
    WCG_O_DetailProviderViewController *detailVc = [[WCG_O_DetailProviderViewController alloc] init];
    detailVc.providerModel = note.userInfo[@"pro"];
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)mapAction
{
    WCG_O_MapViewController *map = [[WCG_O_MapViewController alloc] init];
    // 添加信息
    [self.navigationController pushViewController:map animated:YES];
}

- (void)chatAction
{
    WCG_O_ChatViewController *chat = [[WCG_O_ChatViewController alloc] init];
    // 添加信息
    [self.navigationController pushViewController:chat animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (UIImage*) getBrighterImage:(UIImage *)originalImage
{
    UIImage *brighterImage;
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:originalImage.CGImage];
    
    CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
    [lighten setValue:inputImage forKey:kCIInputImageKey];
    [lighten setValue:@(- 0.2) forKey:@"inputBrightness"];
    
    CIImage *result = [lighten valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];
    brighterImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    
    return brighterImage;
}

- (void)viewDidDisappear:(BOOL)animated
{

}

@end
